@echo off

:: 检查是否以管理员身份运行
net session >nul 2>&1
if %errorLevel% NEQ 0 (
    echo 请以管理员身份运行此批处理文件！
    pause
    exit /b 1
)

:: MySQL配置
set /p mysql_path=请输入MySQL安装路径 [默认: C:\Program Files\MySQL\MySQL Server 8.0\]: 
if "%mysql_path%"=="" set mysql_path=C:\Program Files\MySQL\MySQL Server 8.0\

set /p root_password=请输入MySQL root用户密码: 

:: 1. 创建远程访问用户
 echo 创建远程访问用户...
 mysql -u root -p%root_password% -e "CREATE USER 'remote_user'@'%%' IDENTIFIED BY 'remote_password123';"
 mysql -u root -p%root_password% -e "GRANT ALL PRIVILEGES ON community_service_platform.* TO 'remote_user'@'%%';"
 mysql -u root -p%root_password% -e "FLUSH PRIVILEGES;"
 mysql -u root -p%root_password% -e "SELECT User, Host FROM mysql.user WHERE User = 'remote_user';"

:: 2. 修改MySQL配置文件
 echo 修改MySQL配置文件...
 set config_file=%mysql_path%my.ini

:: 备份配置文件
 copy "%config_file%" "%config_file%.bak" >nul 2>&1

:: 修改bind-address
 (for /f "tokens=*" %%a in ('type "%config_file%"') do (
    echo %%a | findstr /c:"bind-address" >nul
    if errorlevel 1 (
        echo %%a
    ) else (
        echo bind-address = 0.0.0.0
    )
 )) > "%config_file%.tmp"
 move /y "%config_file%.tmp" "%config_file%" >nul 2>&1

:: 3. 配置Windows防火墙
 echo 配置Windows防火墙...
 netsh advfirewall firewall add rule name="MySQL" dir=in action=allow protocol=TCP localport=3306 >nul 2>&1
 netsh advfirewall firewall add rule name="MySQL" dir=out action=allow protocol=TCP localport=3306 >nul 2>&1

:: 4. 重启MySQL服务
 echo 重启MySQL服务...
 net stop mysql >nul 2>&1
 net start mysql >nul 2>&1

:: 5. 获取本机IP地址
 echo 获取本机IP地址...
 ipconfig | findstr /i "IPv4"

 echo. 
 echo ==================================================
 echo 远程数据库配置完成！
 echo 连接信息：
 echo 主机: 上面显示的IPv4地址
 echo 端口: 3306
 echo 用户名: remote_user
 echo 密码: remote_password123
 echo 数据库: community_service_platform
 echo ==================================================

 pause